using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework;

namespace Dune2k1
{
    /// <summary>
    /// Parses Dune 2000 R16 files
    /// </summary>
    /// 
    public class R16Parser
    {
        #region Variables
        string filepath;
        BinaryReader r;
        #endregion

        /// <summary>
        /// Begins parsing  an R16 file
        /// </summary>
        /// <param name="filepath">Location of the file</param>
        /// <param name="device">Graphics device (used for creating textures)</param>
        public R16Parser(string filepath)
        {
            this.filepath = filepath;
            r = new BinaryReader(File.Open(filepath, FileMode.Open));
        }

        /// <summary>
        /// Reads one block of information about a tile.
        /// </summary>
        /// <returns>A tile (if there are any to be read). Returns null if the end of the file is reached.</returns>
        public R16 ReadNextBlock()
        {
            //Check if we've reached the end of the file
            if (r.PeekChar() == -1)
            {
                return null;
            }

            List<byte> raw = new List<byte>();

            //Read the block header
            for (int i = 0; i < 29; i++)
            {
                raw.Add(r.ReadByte());
            }

            //If the block doesn't start with 0x01, then we've got issues :)
            if (raw[0] != 1)
            {
                throw new Exception("Tried to read new block in " + filepath + " failed. Assertion error - block didn't start with 0x01.");
            }

            //Get the texture width and height
            int width, height, size;
            width = BitConverter.ToInt32(raw.ToArray(), 1);
            height = BitConverter.ToInt32(raw.ToArray(), 5);
            size = (width*height)*2;

            //Read texture data
            for (int i = 0; i < size; i++)
            {
                raw.Add(r.ReadByte());
            }

            return new R16(raw.ToArray(), Engine.Graphics.GraphicsDevice);
        }
    }
}